package com.jsbj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.base.Constants;
import com.jsbj.base.ResultBean;
import com.jsbj.enums.ConfigDictTypeEnum;
import com.jsbj.tools.BeanUtils;
import com.jsbj.tools.DateUtils;
import com.jsbj.tools.RequestHeaderUtils;
import com.jsbj.tools.StringUtils;
import com.jsbj.user.entities.*;
import com.jsbj.user.mapper.SysTenantPermissionMapper;
import com.jsbj.user.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 租户菜单表 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2022-03-07
 */
@Service
public class SysTenantPermissionServiceImpl extends ServiceImpl<SysTenantPermissionMapper, SysTenantPermission> implements ISysTenantPermissionService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ISysPermissionAllService sysPermissionAllService;

    @Autowired
    private ISysRolePermissionService sysRolePermissionService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysTenantService sysTenantService;

    @Override
    public List<SysTenantPermission> findMenuListByUserId(String id) {
        return baseMapper.findMenuListByUserId(id);
    }

    @Override
    public List<SysTenantPermission> getByUserIdAndTenant(JSONObject object) {
        String tenantCode = object.getString("tenantCode");
        String userId = object.getString("userId");
        Integer appShow = object.getInteger("appShow");
        List<SysTenantPermission> all ;
        if(appShow!=null && appShow.intValue() == 0){
            all = baseMapper.getByUserIdAndTenantAndApp(tenantCode, userId,appShow);
            // 将系统两个字隐藏
            for (SysTenantPermission sysTenantPermission : all) {
                if (StringUtils.isEmpty(sysTenantPermission.getParentId()) && sysTenantPermission.getMenuName().contains("系统")) {
                    sysTenantPermission.setMenuName(sysTenantPermission.getMenuName().replace("系统", ""));
                }
            }
        }else{
            Integer pcShow = 0;
            all = baseMapper.getByUserIdAndTenantAndPc(tenantCode, userId,pcShow);
        }


        List<SysTenantPermission> ret = new ArrayList<>();
        if(appShow!=null && appShow.intValue() == 0){
            for (SysTenantPermission sysTenantPermission : all) {
                if (StringUtils.isEmpty(sysTenantPermission.getParentId())) {
                    boolean gkFlag = true;
                    // 查询第一级目录（app不展示）
                    List<SysTenantPermission> childs = baseMapper.getByUserIdAndTenantAndAppChild(tenantCode, userId,appShow, sysTenantPermission.getId());
                    for (SysTenantPermission childs1 : childs) {
                        if (childs1.getMenuCode().contains("HOME_PAGE") || childs1.getMenuCode().contains("SJCK")) {
                            gkFlag = false;
                            SysTenantPermission childs11 = getNexNodeNew(childs1, tenantCode, userId, appShow);
                            if (!CollectionUtils.isEmpty(childs11.getChilds())) {
                                List<SysTenantPermission> childs11s = childs11.getChilds();
                                for (SysTenantPermission childs111 : childs11s) {
                                    childs111.setParentId(sysTenantPermission.getId());
                                }
                                sysTenantPermission.setChilds(childs11s);
                                ret.add(sysTenantPermission);
                            }
                        }
                    }
                    if (gkFlag) {
                        SysTenantPermission head = getNexNode(sysTenantPermission, tenantCode, userId, null, appShow);
                        ret.add(head);
                    }
                }
            }
        }  else {
            for (SysTenantPermission sysTenantPermission : all) {
                if (StringUtils.isEmpty(sysTenantPermission.getParentId())) {
                    // 第一个层级，至于第一层，迭代查询最底层
                    SysTenantPermission head = getNexNode(sysTenantPermission, tenantCode, userId, 0, null);
                    ret.add(head);
                }
            }
        }
        return ret;
    }


    @Override
    public Map<String, Object> getAllEndMenu() {
        String tenantCode = RequestHeaderUtils.getTenantCode(request);
        String userId = RequestHeaderUtils.getUserId(request);
        Map<String, Object> ret = new HashMap<>();
        List<SysTenantPermission> sysTenantPermissions = baseMapper.getByUserIdAndTenant(tenantCode, userId);
        for (SysTenantPermission sysTenantPermission : sysTenantPermissions) {
            ret.put(sysTenantPermission.getMenuCode(), sysTenantPermission.getMenuName());
        }
        return ret;
    }

    @Override
    public List<SysTenantPermission> getPZByUserIdAndTenant(JSONObject object) {
        String tenantCode = object.getString("tenantCode");
        String userId = object.getString("userId");
        return baseMapper.getPZByUserIdAndTenant(tenantCode, userId);
    }

    @Override
    public Map<String, Object> getByUserIdAndTenantPC(JSONObject object) {
        LinkedHashMap<String, Object> ret = new LinkedHashMap<>();
        String tenantCode = object.getString("tenantCode");
        String userId = object.getString("userId");
        List<SysTenantPermission> allYw = baseMapper.getByUserIdAndTenantAndPc(tenantCode, userId,0);
        List<SysTenantPermission> ywMenu = new ArrayList<>();
        for (SysTenantPermission sysTenantPermission : allYw) {
            if (StringUtils.isEmpty(sysTenantPermission.getParentId())) {
                // 第一个层级，至于第一层，迭代查询最底层
                SysTenantPermission head = getNexNode(sysTenantPermission, tenantCode, userId, 0, null);
                ywMenu.add(head);
            }
        }

        List<SysTenantPermission> allUser = baseMapper.getUserPageByUserIdAndTenant(tenantCode, userId);

        List<SysTenantPermission> allPZ = baseMapper.getPZByUserIdAndTenant(tenantCode, userId);

        ret.put("userMenu", allUser);
        ret.put("pzMenu", allPZ);
        ret.put("ywMenu", ywMenu);
        return ret;
    }

    @Override
    public SysTenantPermission selectExist(String permissionCode) {
        LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenantPermission::getDisabled, 0);
        queryWrapper.eq(SysTenantPermission::getMenuCode, permissionCode);
        queryWrapper.last(" limit 1");
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<SysTenantPermission> getListData(JSONObject object) {
        String tenantCode = object.getString("tenantCode");
        String menuName = object.getString("menuName");
        String menuTypeValue = object.getString("menuTypeValue");
        LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenantPermission::getDisabled,0);
        queryWrapper.eq(SysTenantPermission::getTenantCode, tenantCode);
        if (StringUtils.isNotEmpty(menuName)) {
            queryWrapper.like(SysTenantPermission::getMenuName, menuName);
        }
        if (StringUtils.isNotEmpty(menuTypeValue)) {
            queryWrapper.eq(SysTenantPermission::getMenuTypeValue, menuTypeValue);
        }
        queryWrapper.orderByAsc(SysTenantPermission::getSort);
        List<SysTenantPermission> tempAll = baseMapper.selectList(queryWrapper);
        List<SysTenantPermission> all = new ArrayList<>();
        // 查询菜单类型描述
        List<SysDictData> sysDictDataList = sysDictDataService.getDataByKey("menuType");
        for (SysTenantPermission sysTenantPermission : tempAll) {
            if (StringUtils.isEmpty(sysTenantPermission.getParentId())) {
                sysTenantPermission.setUpdateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", sysTenantPermission.getUpdateTime()));
                sysTenantPermission.setPermissionTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.MENUTYPE.getCode(), sysTenantPermission.getMenuTypeValue()));
                for (SysDictData sysDictData : sysDictDataList) {
                    if (sysTenantPermission.getMenuTypeValue().equals(sysDictData.getDicValue().toString())) {
                        sysTenantPermission.setMenuTypeDesc(sysDictData.getDicDesc());
                        break;
                    }
                }
                List<SysTenantPermission> children = getChildren(sysTenantPermission.getId(), tempAll, sysDictDataList);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(children)) {
                    sysTenantPermission.setChilds(children);
                    sysTenantPermission.setDel(false);
                } else {
                    sysTenantPermission.setDel(true);
                }
                all.add(sysTenantPermission);
            }
        }
        return all;
    }

    @Override
    public ResultBean<JSONObject> saveOrUpdateYY(TenantPermissionParams tenantPermissionParams) {
        // 校验必填
        List<TenantPermissionParamsChild> menuIdList = tenantPermissionParams.getMenuIdList();
        if (StringUtils.isEmpty(tenantPermissionParams.getIsSystemMenu()) || StringUtils.isEmpty(tenantPermissionParams.getTenantCode())
        || CollectionUtils.isEmpty(menuIdList)) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        // 校验是否菜单编码已在项目存在
        List<String> menuIds = getMenuIds(menuIdList);
        LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SysTenantPermission::getMenuName);
        queryWrapper.eq(SysTenantPermission::getDisabled,0);
        queryWrapper.eq(SysTenantPermission::getTenantCode, tenantPermissionParams.getTenantCode());
        queryWrapper.in(SysTenantPermission::getId, menuIds);
        queryWrapper.eq(SysTenantPermission::getMenuTypeValue, 2);
        queryWrapper.inSql(SysTenantPermission::getMenuCode, "select menu_code from sys_tenant_permission where disabled=0 and menu_type_value = 2 and tenant_code='"+tenantPermissionParams.getTenantCode()+"'");
        List<SysTenantPermission> existsList = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(existsList)) {
            List<String> menuNames = existsList.stream().map(SysTenantPermission::getMenuName).collect(Collectors.toList());
            return new ResultBean<>().build(menuNames.stream().collect(Collectors.joining(",")) + "菜单已存在，请刷新后重试！");
        }

        // 开始保存，注意树形结构
        LambdaQueryWrapper<SysTenantPermission> saveWrapper = new LambdaQueryWrapper<>();
        saveWrapper.eq(SysTenantPermission::getDisabled,0);
        saveWrapper.in(SysTenantPermission::getId, menuIds);
        List<SysTenantPermission> saveList = baseMapper.selectList(saveWrapper);
        for (TenantPermissionParamsChild child : menuIdList) {
            // 如果上级目录不为空，那么第一层菜单全部要放在上级目录下面
            // 校验节点是否存在，存在的话，不保存,否则，直接保存
            SysTenantPermission parentInfo = saveAndGetInfo(saveList, child.getId(), tenantPermissionParams.getTenantCode(), tenantPermissionParams.getParentId(), tenantPermissionParams.getIsSystemMenu());
            saveChildInfo(child, parentInfo.getId(), saveList, tenantPermissionParams.getTenantCode(), tenantPermissionParams.getIsSystemMenu());
        }

        return new ResultBean<>().success("处理成功！");
    }

    private void saveChildInfo(TenantPermissionParamsChild parent, String parentId, List<SysTenantPermission> saveList, String tenantCode, String isSystemMenu) {
        List<TenantPermissionParamsChild> menuIdList = parent.getMenuIdList();
        if (null != menuIdList) {
            for (TenantPermissionParamsChild child : menuIdList) {
                SysTenantPermission parentInfo = saveAndGetInfo(saveList, child.getId(), tenantCode, parentId, isSystemMenu);
                saveChildInfo(child, parentInfo.getId(), saveList, tenantCode, isSystemMenu);
            }
        }
    }

    private SysTenantPermission saveAndGetInfo(List<SysTenantPermission> saveList, String id, String tenantCode, String parentId, String isSystemMenu) {
        SysTenantPermission sysTenantPermission = null;
        for (SysTenantPermission sysTenantPermission1 : saveList) {
            if (id.equals(sysTenantPermission1.getId())) {
                sysTenantPermission = sysTenantPermission1;
                break;
            }
        }
        if (null != sysTenantPermission) {
            LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysTenantPermission::getDisabled,0);
            queryWrapper.eq(SysTenantPermission::getTenantCode, tenantCode);
            queryWrapper.eq(SysTenantPermission::getMenuCode, sysTenantPermission.getMenuCode());
            queryWrapper.last(" limit 1");
            SysTenantPermission exists = baseMapper.selectOne(queryWrapper);
            if (null != exists) {
                return exists;
            }
            // 开始保存
            String userId = RequestHeaderUtils.getUserId(request);
            sysTenantPermission.setId(null);
            sysTenantPermission.setParentId(parentId);
            sysTenantPermission.setTenantCode(tenantCode);
            sysTenantPermission.setIsSystemMenu(isSystemMenu);
            sysTenantPermission.setCreaterId(userId);
            sysTenantPermission.setUpdateId(userId);
            sysTenantPermission.setCreateTime(new Date());
            sysTenantPermission.setUpdateTime(new Date());
            baseMapper.insert(sysTenantPermission);

            saveSuperRoleData(sysTenantPermission.getId(), tenantCode, userId);
        }
        return sysTenantPermission;
    }

    private void saveSuperRoleData(String tenantPermissionId, String tenantCode, String userId) {
        String roleCode = "ROLE_SUPER_" + tenantCode;
        // 查询id
        SysRole sysRole = sysRoleService.getByCode(roleCode);
        if (null == sysRole) {
            SysTenant sysTenant = sysTenantService.getByTenantCode(tenantCode);
            // 插入新角色
            sysRole = new SysRole();
            sysRole.setRoleName(sysTenant.getTenantName() + "超管角色");
            sysRole.setRoleCode(roleCode);
            sysRole.setRoleType("1");
            sysRole.setSort(0);
            sysRole.setCreaterId(userId);
            sysRole.setCreateTime(new Date());
            sysRole.setUpdateId(userId);
            sysRole.setUpdateTime(new Date());
            sysRoleService.save(sysRole);
        }
        sysRolePermissionService.insertData(tenantPermissionId, sysRole.getId(), userId);

    }

    private List<String> getMenuIds(List<TenantPermissionParamsChild> menuIdList) {
        List<String> ids = new ArrayList<>();
        for (TenantPermissionParamsChild tenantPermissionParamsChild : menuIdList) {
            ids.add(tenantPermissionParamsChild.getId());
            if (!CollectionUtils.isEmpty(tenantPermissionParamsChild.getMenuIdList())) {
                List<String> ids1 = getMenuIds(tenantPermissionParamsChild.getMenuIdList());
                if (!CollectionUtils.isEmpty(ids1)) {
                    ids.addAll(ids1);
                }
            }
        }
        return ids;
    }

    @Override
    public List<String> alraedyChoose(String tenantCode) {
        return baseMapper.alraedyChoose(tenantCode);
    }

    @Override
    public ResultBean<JSONObject> saveOrUpdateZJD(TenantPermissionParams tenantPermissionParams) {
        // 校验必填
        if (StringUtils.isEmpty(tenantPermissionParams.getMenuTypeValue()) || StringUtils.isEmpty(tenantPermissionParams.getTenantCode())) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        String userId = RequestHeaderUtils.getUserId(request);
        if ("1".equals(tenantPermissionParams.getMenuTypeValue())) {
            // 目录
            if (StringUtils.isEmpty(tenantPermissionParams.getMenuCode()) || StringUtils.isEmpty(tenantPermissionParams.getMenuName()) || null == tenantPermissionParams.getSort()) {
                return new ResultBean<>().build("必填项不能为空！");
            }
            // 校验编码是否已存在
            LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysTenantPermission::getDisabled,0);
            queryWrapper.eq(SysTenantPermission::getTenantCode, tenantPermissionParams.getTenantCode());
            queryWrapper.eq(SysTenantPermission::getMenuCode, tenantPermissionParams.getMenuCode());
            queryWrapper.last(" limit 1");
            SysTenantPermission exists = baseMapper.selectOne(queryWrapper);
            if (null != exists) {
                return new ResultBean<>().build("编码已存在，请修改后重新提交！");
            }
            SysTenantPermission sysTenantPermission = new SysTenantPermission();
            sysTenantPermission.setTenantCode(tenantPermissionParams.getTenantCode());
            sysTenantPermission.setMenuCode(tenantPermissionParams.getMenuCode());
            sysTenantPermission.setMenuName(tenantPermissionParams.getMenuName());
            sysTenantPermission.setParentId(tenantPermissionParams.getParentId());
            sysTenantPermission.setSort(tenantPermissionParams.getSort());
            sysTenantPermission.setMenuTypeKey(ConfigDictTypeEnum.MENUTYPE.getCode());
            sysTenantPermission.setMenuTypeValue(tenantPermissionParams.getMenuTypeValue());
            sysTenantPermission.setCreaterId(userId);
            sysTenantPermission.setUpdateId(userId);
            baseMapper.insert(sysTenantPermission);

            saveSuperRoleData(sysTenantPermission.getId(), tenantPermissionParams.getTenantCode(), userId);
        } else {
            List<TenantPermissionParamsChild> menuIdList = tenantPermissionParams.getMenuIdList();
            if (StringUtils.isEmpty(tenantPermissionParams.getIsSystemMenu()) || CollectionUtils.isEmpty(menuIdList)) {
                return new ResultBean<>().build("必填项不能为空！");
            }
            // 校验是否菜单编码已在项目存在
            List<String> menuIds = getMenuIds(menuIdList);
            LambdaQueryWrapper<SysPermissionAll> allQueryWrapper = new LambdaQueryWrapper<>();
            allQueryWrapper.eq(SysPermissionAll::getDisabled,0);
            allQueryWrapper.in(SysPermissionAll::getId, menuIds);
            List<SysPermissionAll> sysPermissionAlls = sysPermissionAllService.list(allQueryWrapper);
            List<String> menuCodes = sysPermissionAlls.stream().map(SysPermissionAll::getPermissionCode).collect(Collectors.toList());

            LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(SysTenantPermission::getMenuName);
            queryWrapper.eq(SysTenantPermission::getDisabled,0);
            queryWrapper.eq(SysTenantPermission::getTenantCode, tenantPermissionParams.getTenantCode());
            queryWrapper.in(SysTenantPermission::getMenuCode, menuCodes);
            queryWrapper.eq(SysTenantPermission::getMenuTypeValue, 2);
            List<SysTenantPermission> existsList = baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(existsList)) {
                List<String> menuNames = existsList.stream().map(SysTenantPermission::getMenuName).collect(Collectors.toList());
                return new ResultBean<>().build(menuNames.stream().collect(Collectors.joining(",")) + "菜单已存在，请刷新后重试！");
            }
            // 开始保存
            for (TenantPermissionParamsChild child : menuIdList) {
                // 校验节点是否存在，存在的话，不保存,否则，直接保存
                SysTenantPermission parentInfo = saveZJDAndGetInfo(sysPermissionAlls, child.getId()
                        , tenantPermissionParams.getTenantCode(), tenantPermissionParams.getParentId(), tenantPermissionParams.getIsSystemMenu());
                List<TenantPermissionParamsChild> children = child.getMenuIdList();
                if (null != children) {
                    for (TenantPermissionParamsChild children1 : children) {
                        saveZJDAndGetInfo(sysPermissionAlls, children1.getId()
                                , tenantPermissionParams.getTenantCode(), parentInfo.getId(), tenantPermissionParams.getIsSystemMenu());
                    }
                }
            }
        }
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public ResultBean<JSONObject> saveOrUpdateML(TenantPermissionParams tenantPermissionParams) {
        if (StringUtils.isEmpty(tenantPermissionParams.getTenantCode()) || StringUtils.isEmpty(tenantPermissionParams.getMenuCode())
                || StringUtils.isEmpty(tenantPermissionParams.getMenuName()) || null == tenantPermissionParams.getSort()
                || null == tenantPermissionParams.getPcShow() || null == tenantPermissionParams.getAppShow()) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        tenantPermissionParams.setMenuTypeValue("1");
        String userId = RequestHeaderUtils.getUserId(request);
        // 校验编码是否已存在
        LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenantPermission::getDisabled,0);
        queryWrapper.eq(SysTenantPermission::getTenantCode, tenantPermissionParams.getTenantCode());
        queryWrapper.eq(SysTenantPermission::getMenuCode, tenantPermissionParams.getMenuCode());
        queryWrapper.last(" limit 1");
        SysTenantPermission exists = baseMapper.selectOne(queryWrapper);
        if (null != exists) {
            return new ResultBean<>().build("编码已存在，请修改后重新提交！");
        }
        SysTenantPermission sysTenantPermission = new SysTenantPermission();
        sysTenantPermission.setSort(tenantPermissionParams.getSort());
        sysTenantPermission.setTenantCode(tenantPermissionParams.getTenantCode());
        sysTenantPermission.setMenuCode(tenantPermissionParams.getMenuCode());
        sysTenantPermission.setMenuName(tenantPermissionParams.getMenuName());
        sysTenantPermission.setParentId(tenantPermissionParams.getParentId());
        sysTenantPermission.setMenuTypeKey(ConfigDictTypeEnum.MENUTYPE.getCode());
        sysTenantPermission.setMenuTypeValue(tenantPermissionParams.getMenuTypeValue());
        sysTenantPermission.setPcShow(tenantPermissionParams.getPcShow());
        sysTenantPermission.setAppShow(tenantPermissionParams.getAppShow());
        sysTenantPermission.setCreaterId(userId);
        sysTenantPermission.setUpdateId(userId);
        baseMapper.insert(sysTenantPermission);

        saveSuperRoleData(sysTenantPermission.getId(), tenantPermissionParams.getTenantCode(), userId);
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public SysTenantPermission getDetail(String id) {
        SysTenantPermission sysTenantPermission = baseMapper.selectById(id);
        sysTenantPermission.setUpdateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", sysTenantPermission.getUpdateTime()));
        sysTenantPermission.setPermissionTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.MENUTYPE.getCode(), sysTenantPermission.getMenuTypeValue()));
        return sysTenantPermission;
    }

    @Override
    public ResultBean<JSONObject> deleteData(String id) {
        SysTenantPermission sysTenantPermission = baseMapper.selectById(id);
        // 判断是否是子节点
        LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenantPermission::getDisabled,0);
        queryWrapper.eq(SysTenantPermission::getParentId, sysTenantPermission.getId());
        queryWrapper.last(" limit 1");
        List<SysTenantPermission> child = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(child)) {
            return new ResultBean<>().build("当前节点非子节点，无法删除！");
        }
        // 判断是否已被角色引用
//        LambdaQueryWrapper<SysRolePermission> queryWrapper1 = new LambdaQueryWrapper<>();
//        queryWrapper1.eq(SysRolePermission::getDisabled,0);
//        queryWrapper1.eq(SysRolePermission::getSysTenantPermissionId, id);
//        queryWrapper1.last(" limit 1");
//        SysRolePermission sysRolePermission = sysRolePermissionService.getOne(queryWrapper1);
//        if (null != sysRolePermission) {
//            return new ResultBean<>().build("当前菜单已被角色引用，无法删除！");
//        }

        // 删除权限角色表
        LambdaUpdateWrapper<SysRolePermission> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysRolePermission::getDisabled,0);
        updateWrapper.eq(SysRolePermission::getSysTenantPermissionId, id);
        SysRolePermission sysRolePermission = new SysRolePermission();
        sysRolePermission.setDisabled(1);
        sysRolePermission.setUpdateTime(new Date());
        sysRolePermissionService.update(sysRolePermission, updateWrapper);

        sysTenantPermission.setDisabled(1);
        String userId = RequestHeaderUtils.getUserId(request);
        sysTenantPermission.setUpdateId(userId);
        sysTenantPermission.setUpdateTime(new Date());
        baseMapper.updateById(sysTenantPermission);
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public ResultBean<JSONObject> updateData(SysTenantPermission sysTenantPermission) {
        // 校验必填
        if (StringUtils.isEmpty(sysTenantPermission.getMenuTypeValue()) || StringUtils.isEmpty(sysTenantPermission.getId())
                || StringUtils.isEmpty(sysTenantPermission.getMenuName()) || null == sysTenantPermission.getSort()) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        SysTenantPermission updateInfo = baseMapper.selectById(sysTenantPermission.getId());
        String userId = RequestHeaderUtils.getUserId(request);
        if ("2".equals(sysTenantPermission.getMenuTypeValue())) {
            if (StringUtils.isEmpty(sysTenantPermission.getIsFrame()) || StringUtils.isEmpty(sysTenantPermission.getPath()) || StringUtils.isEmpty(sysTenantPermission.getActiveRule())
                    || StringUtils.isEmpty(sysTenantPermission.getOpenType()) || StringUtils.isEmpty(sysTenantPermission.getIsSystemMenu())
            || null == sysTenantPermission.getPcShow() || null == sysTenantPermission.getAppShow()) {
                return new ResultBean<>().build("必填项不能为空！");
            }
        } else if ("4".equals(sysTenantPermission.getMenuTypeValue())) {
            if (StringUtils.isEmpty(sysTenantPermission.getIsFrame()) || StringUtils.isEmpty(sysTenantPermission.getPath()) || StringUtils.isEmpty(sysTenantPermission.getActiveRule())
                    || StringUtils.isEmpty(sysTenantPermission.getOpenType())) {
                return new ResultBean<>().build("必填项不能为空！");
            }
        }
        BeanUtils.copyPropertiesIgnoreNull(sysTenantPermission, updateInfo);
        updateInfo.setUpdateId(userId);
        updateInfo.setUpdateTime(new Date());
        baseMapper.updateById(updateInfo);
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public List<LinkedHashMap<String, Object>> getByUserIdAndTenantPCNew(JSONObject object) {
        List<LinkedHashMap<String, Object>> ret = new ArrayList<>();

        String tenantCode = object.getString("tenantCode");
        String userId = object.getString("userId");
        // 业务菜单
        List<SysTenantPermission> allYwHead = baseMapper.getByUserIdAndTenantAndPcHead(tenantCode, userId,0);
        // 查询所有菜单，带入循环
        List<SysTenantPermission> allYw = baseMapper.getByUserIdAndTenantAndPc(tenantCode, userId,0);

        List<SysTenantPermission> ywMenu = new ArrayList<>();
        for (SysTenantPermission sysTenantPermission : allYwHead) {
            if (StringUtils.isEmpty(sysTenantPermission.getParentId())) {
                // 第一个层级，至于第一层，迭代查询最底层
//                SysTenantPermission head = getNexNode(sysTenantPermission, tenantCode, userId, 0, null);
                SysTenantPermission head = getNexNodePcNew(sysTenantPermission, allYw);
                if (!CollectionUtils.isEmpty(head.getChilds())) {
                    ywMenu.add(head);
                }
            }
        }

        // 配置中心
        List<SysTenantPermission> allPZ = baseMapper.getPZByUserIdAndTenant(tenantCode, userId);

        if (!CollectionUtils.isEmpty(ywMenu)) {
            LinkedHashMap<String, Object> yw = new LinkedHashMap<>();
            yw.put("menuName", "业务中心");
            yw.put("menuType", 0);
            yw.put("child", ywMenu);
            ret.add(yw);
        }

        // 首页
        List<SysTenantPermission> allUser = baseMapper.getUserPageByUserIdAndTenant(tenantCode, userId);
        if (!CollectionUtils.isEmpty(allUser)) {
            LinkedHashMap<String, Object> user = new LinkedHashMap<>();
            user.put("menuName", "数据看板");
            user.put("menuType", 2);
            user.put("activeRule", allUser.get(0).getActiveRule());
            user.put("id", allUser.get(0).getId());
            user.put("menuCode", allUser.get(0).getMenuCode());
            user.put("path", allUser.get(0).getPath());
            user.put("tenantCode", allUser.get(0).getTenantCode());
            user.put("isFrame", allUser.get(0).getIsFrame());
            user.put("openType", allUser.get(0).getOpenType());
            user.put("child", new ArrayList<>());
            ret.add(user);
        }

        if (!CollectionUtils.isEmpty(allPZ)) {
            LinkedHashMap<String, Object> pz = new LinkedHashMap<>();
            pz.put("menuName", "配置中心");
            pz.put("menuType", 1);
            pz.put("child", allPZ);
            ret.add(pz);
        }

        // 大屏
        List<SysTenantPermission> bigScreen = baseMapper.getBigScreenByUserIdAndTenant(tenantCode, userId);
        if (!CollectionUtils.isEmpty(bigScreen)) {
            LinkedHashMap<String, Object> screen = new LinkedHashMap<>();
            screen.put("menuName", "大屏");
            screen.put("menuType", 3);
            screen.put("activeRule", bigScreen.get(0).getActiveRule());
            screen.put("id", bigScreen.get(0).getId());
            screen.put("menuCode", bigScreen.get(0).getMenuCode());
            screen.put("path", bigScreen.get(0).getPath());
            screen.put("tenantCode", bigScreen.get(0).getTenantCode());
            screen.put("isFrame", bigScreen.get(0).getIsFrame());
            screen.put("openType", bigScreen.get(0).getOpenType());
            screen.put("child", new ArrayList<>());
            ret.add(screen);
        }

        return ret;
    }

    private SysTenantPermission getNexNodePcNew(SysTenantPermission sysTenantPermission, List<SysTenantPermission> allYw) {
        List<SysTenantPermission> childs = new ArrayList<>();
        for (SysTenantPermission allYwMap : allYw) {
            if (!"4".equals(allYwMap.getMenuTypeValue()) && sysTenantPermission.getId().equals(allYwMap.getParentId())) {
                childs.add(allYwMap);
            }
        }
        if (!CollectionUtils.isEmpty(childs)) {
            sysTenantPermission.setChilds(childs);
            for (SysTenantPermission child : childs) {
                this.getNexNodePcNew(child, allYw);
            }
        }
        return sysTenantPermission;
    }

    @Override
    public String getMenuNameByCode(String tenantCode, String menuCode) {
        LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenantPermission::getDisabled, 0);
        queryWrapper.eq(SysTenantPermission::getTenantCode, tenantCode);
        queryWrapper.eq(SysTenantPermission::getMenuCode, menuCode);
        queryWrapper.last(" limit 1");
        SysTenantPermission sysTenantPermission = baseMapper.selectOne(queryWrapper);
        if (null != sysTenantPermission) {
            return sysTenantPermission.getMenuName();
        }
        return "";
    }

    @Override
    public List<SysTenantPermission> getMLListData(JSONObject object) {
        String tenantCode = object.getString("tenantCode");
        LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenantPermission::getDisabled,0);
        queryWrapper.eq(SysTenantPermission::getTenantCode, tenantCode);
        queryWrapper.eq(SysTenantPermission::getMenuTypeValue, 1);
        queryWrapper.orderByAsc(SysTenantPermission::getSort);
        List<SysTenantPermission> tempAll = baseMapper.selectList(queryWrapper);
        List<SysTenantPermission> all = new ArrayList<>();
        // 查询菜单类型描述
        List<SysDictData> sysDictDataList = sysDictDataService.getDataByKey("menuType");
        for (SysTenantPermission sysTenantPermission : tempAll) {
            if (StringUtils.isEmpty(sysTenantPermission.getParentId())) {
                sysTenantPermission.setUpdateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", sysTenantPermission.getUpdateTime()));
                sysTenantPermission.setPermissionTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.MENUTYPE.getCode(), sysTenantPermission.getMenuTypeValue()));
                for (SysDictData sysDictData : sysDictDataList) {
                    if (sysTenantPermission.getMenuTypeValue().equals(sysDictData.getDicValue().toString())) {
                        sysTenantPermission.setMenuTypeDesc(sysDictData.getDicDesc());
                        break;
                    }
                }
                List<SysTenantPermission> children = getChildren(sysTenantPermission.getId(), tempAll, sysDictDataList);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(children)) {
                    sysTenantPermission.setChilds(children);
                    sysTenantPermission.setDel(false);
                } else {
                    sysTenantPermission.setDel(true);
                }
                all.add(sysTenantPermission);
            }
        }
        return all;

    }

    @Override
    public List<SysTenantPermission> getTenantPermissionsByRoleId(String roleId, String tenantCode) {

        List<SysTenantPermission> tempAll = baseMapper.getTenantPermissionsByRoleId(roleId, tenantCode);
        List<SysTenantPermission> all = new ArrayList<>();
        // 查询菜单类型描述
        List<SysDictData> sysDictDataList = sysDictDataService.getDataByKey("menuType");
        for (SysTenantPermission sysTenantPermission : tempAll) {
            if (StringUtils.isEmpty(sysTenantPermission.getParentId())) {
                sysTenantPermission.setUpdateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", sysTenantPermission.getUpdateTime()));
                sysTenantPermission.setPermissionTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.MENUTYPE.getCode(), sysTenantPermission.getMenuTypeValue()));
                for (SysDictData sysDictData : sysDictDataList) {
                    if (sysTenantPermission.getMenuTypeValue().equals(sysDictData.getDicValue().toString())) {
                        sysTenantPermission.setMenuTypeDesc(sysDictData.getDicDesc());
                        break;
                    }
                }
                List<SysTenantPermission> children = getChildren(sysTenantPermission.getId(), tempAll, sysDictDataList);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(children)) {
                    sysTenantPermission.setChilds(children);
                    sysTenantPermission.setDel(false);
                } else {
                    sysTenantPermission.setDel(true);
                }
                all.add(sysTenantPermission);
            }
        }
        return all;
    }

    @Override
    public void dealExpertMenu(String tenantCode, String roleId) {
        SysTenantPermission sysTenantPermission = getByTM(tenantCode, "PZGC_RWCL");
        if (null == sysTenantPermission) {
            SysPermissionAll sysPermissionAll = sysPermissionAllService.getByMenuCode("PZGC_RWCL");
            SysTenantPermission demo = getByTM(tenantCode, "PZGC_ZJCJ");

            sysTenantPermission = new SysTenantPermission();
            sysTenantPermission.setTenantCode(tenantCode);
            sysTenantPermission.setParentId(demo.getParentId());
            sysTenantPermission.setIsSystemMenu(demo.getIsSystemMenu());
            sysTenantPermission.setMenuCode(sysPermissionAll.getPermissionCode());
            sysTenantPermission.setMenuName(sysPermissionAll.getPermissionName());
            sysTenantPermission.setMenuTypeKey(sysPermissionAll.getPermissionTypeKey());
            sysTenantPermission.setMenuTypeValue(sysPermissionAll.getPermissionTypeValue());
            sysTenantPermission.setMenuTypeValue(sysPermissionAll.getPermissionTypeValue());
            sysTenantPermission.setIsFrame(sysPermissionAll.getIsFrame());
            sysTenantPermission.setPath(sysPermissionAll.getPath());
            sysTenantPermission.setAppPath(sysPermissionAll.getAppPath());
            sysTenantPermission.setIsH5(sysPermissionAll.getIsH5());
            sysTenantPermission.setActiveRule(sysPermissionAll.getActiveRule());
            sysTenantPermission.setOpenType(sysPermissionAll.getOpenType());
            sysTenantPermission.setSort(sysPermissionAll.getSort());
            sysTenantPermission.setDisabled(0);
            sysTenantPermission.setCreaterId("sys");
            sysTenantPermission.setUpdateId("sys");
            baseMapper.insert(sysTenantPermission);

            // 父级目录
            insertParentData(roleId, demo.getParentId());
        }
        sysRolePermissionService.insertData(sysTenantPermission.getId(), roleId, "sys");
        // 插入父级权限
        insertParentRole(sysTenantPermission.getParentId(), roleId, "sys");
        // 插入父级租户对应的数据看板
        LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenantPermission::getDisabled, 0);
        queryWrapper.eq(SysTenantPermission::getTenantCode, Constants.PARENT_TENANT_CODE);
        queryWrapper.eq(SysTenantPermission::getMenuCode, "HOME_PAGE");
        queryWrapper.last(" limit 1");
        SysTenantPermission parentHome = baseMapper.selectOne(queryWrapper);
        if (null != parentHome) {
            sysRolePermissionService.insertData(parentHome.getId(), roleId, "sys");
        }
    }

    private void insertParentRole(String parentId, String roleId, String userId) {
        if (StringUtils.isNotEmpty(parentId)) {
            sysRolePermissionService.insertData(parentId, roleId, userId);
            SysTenantPermission sysTenantPermission = baseMapper.selectById(parentId);
            insertParentRole(sysTenantPermission.getParentId(), roleId, "sys");
        }
    }

    private void insertParentData(String roleId, String id) {
        if (StringUtils.isNotEmpty(id)) {
            SysTenantPermission demo = baseMapper.selectById(id);
            sysRolePermissionService.insertData(demo.getId(), roleId, "sys");
            if (StringUtils.isNotEmpty(demo.getParentId())) {
                insertParentData(roleId, demo.getParentId());
            }
        }
    }

    private SysTenantPermission getByTM(String tenantCode, String menuCode) {
        LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenantPermission::getMenuCode, menuCode);
        queryWrapper.eq(SysTenantPermission::getTenantCode, tenantCode);
        queryWrapper.eq(SysTenantPermission::getDisabled, 0);
        queryWrapper.last(" limit 1");
        SysTenantPermission sysTenantPermission = baseMapper.selectOne(queryWrapper);
        return sysTenantPermission;
    }

    private SysTenantPermission saveZJDAndGetInfo(List<SysPermissionAll> sysPermissionAlls, String id, String tenantCode, String parentId, String isSystemMenu) {
        String userId = RequestHeaderUtils.getUserId(request);
        SysTenantPermission sysTenantPermission = null;
        for (SysPermissionAll sysPermissionAll : sysPermissionAlls) {
            if (id.equals(sysPermissionAll.getId())) {
                sysTenantPermission = new SysTenantPermission();
                sysTenantPermission.setTenantCode(tenantCode);
                sysTenantPermission.setParentId(parentId);
                sysTenantPermission.setIsSystemMenu(isSystemMenu);
                sysTenantPermission.setMenuCode(sysPermissionAll.getPermissionCode());
                sysTenantPermission.setMenuName(sysPermissionAll.getPermissionName());
                sysTenantPermission.setMenuTypeKey(sysPermissionAll.getPermissionTypeKey());
                sysTenantPermission.setMenuTypeValue(sysPermissionAll.getPermissionTypeValue());
                sysTenantPermission.setMenuTypeValue(sysPermissionAll.getPermissionTypeValue());
                sysTenantPermission.setIsFrame(sysPermissionAll.getIsFrame());
                sysTenantPermission.setPath(sysPermissionAll.getPath());
                sysTenantPermission.setAppPath(sysPermissionAll.getAppPath());
                sysTenantPermission.setIsH5(sysPermissionAll.getIsH5());
                sysTenantPermission.setActiveRule(sysPermissionAll.getActiveRule());
                sysTenantPermission.setOpenType(sysPermissionAll.getOpenType());
                sysTenantPermission.setSort(sysPermissionAll.getSort());
                sysTenantPermission.setCreaterId(userId);
                sysTenantPermission.setUpdateId(userId);
                baseMapper.insert(sysTenantPermission);

                saveSuperRoleData(sysTenantPermission.getId(), tenantCode, userId);
                break;
            }
        }
        return sysTenantPermission;
    }

    private List<SysTenantPermission> getChildren(String parentId, List<SysTenantPermission> tempAll, List<SysDictData> sysDictDataList) {
        List<SysTenantPermission> ret = new ArrayList<>();
        for (SysTenantPermission child : tempAll) {
            if (StringUtils.isNotEmpty(child.getParentId()) && parentId.equals(child.getParentId())) {
                child.setPermissionTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.MENUTYPE.getCode(), child.getMenuTypeValue()));
                child.setUpdateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", child.getUpdateTime()));
                for (SysDictData sysDictData : sysDictDataList) {
                    if (child.getMenuTypeValue().equals(sysDictData.getDicValue().toString())) {
                        child.setMenuTypeDesc(sysDictData.getDicDesc());
                        break;
                    }
                }
                List<SysTenantPermission> children = getChildren(child.getId(), tempAll, sysDictDataList);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(children)) {
                    child.setChilds(children);
                    child.setDel(false);
                } else {
                    child.setDel(true);
                }
                ret.add(child);
            }
        }
        return ret;
    }

    private SysTenantPermission getNexNode(SysTenantPermission sysTenantPermission, String tenantCode, String userId, Integer pcShow, Integer appShow) {
        // 查询所有以此为父级的所有子节点
        List<SysTenantPermission> childs = null;
        if (null != pcShow) {
            childs = baseMapper.getByUserIdAndTenantAndPcChild(tenantCode, userId,pcShow, sysTenantPermission.getId());
        }
        if (null != appShow) {
            childs = baseMapper.getByUserIdAndTenantAndAppChild(tenantCode, userId,appShow, sysTenantPermission.getId());
        }
        if (!CollectionUtils.isEmpty(childs)) {
            sysTenantPermission.setChilds(childs);
            for (SysTenantPermission child : childs) {
                this.getNexNode(child, tenantCode, userId, pcShow, appShow);
            }
        }
        return sysTenantPermission;
    }

    private SysTenantPermission getNexNodeNew(SysTenantPermission sysTenantPermission, String tenantCode, String userId, Integer appShow) {
        // 查询所有以此为父级的所有子节点
        List<SysTenantPermission> childs = baseMapper.getByUserIdAndTenantAndAppChild(tenantCode, userId,appShow, sysTenantPermission.getId());
        if (!CollectionUtils.isEmpty(childs)) {
            sysTenantPermission.setChilds(childs);
            for (SysTenantPermission child : childs) {
                this.getNexNodeNew(child, tenantCode, userId, appShow);
            }
        }
        return sysTenantPermission;
    }

    @Override
    public List<SysTenantPermission> getButtonByUserIdAndTenantAndMenuCode(JSONObject object) {
        String tenantCode = object.getString("tenantCode");
        String menuCode = object.getString("menuCode");
        String userId = object.getString("userId");
        Integer appShow = object.getInteger("appShow");
        Integer pcShow = object.getInteger("pcShow");

        Map<String,Object> params = new HashMap<>();
        params.put("tenantCode",tenantCode);
        params.put("menuCode",menuCode);
        params.put("userId",userId);
        params.put("appShow",appShow);
        params.put("pcShow",pcShow);

        return baseMapper.getButtonByUserIdAndTenantAndMenuCode(params);
    }

    @Override
    public List<SysTenantPermission> getByTenantCodeAndPc(String tenantCode) {

        // 业务菜单
        List<SysTenantPermission> allYwHead = baseMapper.getByTenantCodeAndPcHead(tenantCode, 0);
        // 查询所有菜单，带入循环
        List<SysTenantPermission> allYw = baseMapper.getByTenantCodeAndPc(tenantCode,0);
        // 首页
        List<SysTenantPermission> allUser = baseMapper.getUserPageByTenantCode(tenantCode);

        List<SysTenantPermission> ywMenu = new ArrayList<>();
        for (SysTenantPermission sysTenantPermission : allYwHead) {

            if(!"PZGCGLXT".equals(sysTenantPermission.getMenuCode())){//只处理品质工程的菜单
                continue;
            }
            if (StringUtils.isEmpty(sysTenantPermission.getParentId())) {
                // 第一个层级，至于第一层，迭代查询最底层
//                SysTenantPermission head = getNexNode(sysTenantPermission, tenantCode, userId, 0, null);
                SysTenantPermission head = getNexNodePcNew(sysTenantPermission, allYw);
                if (!CollectionUtils.isEmpty(head.getChilds())) {
                    ywMenu.add(head);
                }
            }
        }
        ywMenu.addAll(allUser);

        return ywMenu;
    }
}
